import React, { Component, PropTypes } from 'react';
import { Row, Col, Tabs,message} from 'antd';
const TabPane = Tabs.TabPane;
import $ from 'jquery'
import config from '../../config/config';

// 引入Cookie
import Cookie from 'js-cookie'


import styles from './Editor.less'
import classnames from 'classnames/bind'
let cx = classnames.bind(styles);

class Ueditor extends Component {
    constructor(props) {
        super(props);
        this.editItem = null;
        this.state = {
            isSubmit:true,
            editable: (props.editable === false ? false : true),
            html: props.html,
            isShowPhone: (props.isShowPhone === false ? false : true),
            tabList: [
                { tabName: '5.5寸以上', claBox: 'Xphone_box', phone: 'phone1' },
                { tabName: '5.5寸屏', claBox: 'Bphone_box', phone: 'phone2' },
                { tabName: '5寸及以下', claBox: 'Mphone_box', phone: 'phone3' }]
        };
    }
    componentDidMount() {
        var me = this;
        setTimeout(function(){
            me.editor = me.initEditor()
        },500)

        
        if (!(!!window.ActiveXObject || "ActiveXObject" in window)) {//如果不是IE浏览器
            $(".phone_content").each(function () {//使外部样式失效，达到屏蔽效果
                //console.log('componentDidMount foreach'+me.props.html)
                this.attachShadow({ mode: 'open' });
                this.shadowRoot.innerHTML = "<style>img{height:auto!important;} *{max-width:100%!important;}</style>" + me.props.html
            })
        }
    }
    componentWillUnmount() {
        // 组件卸载后，清除放入库的id
        UE.delEditor(this.props.id);
    }

    componentDidUpdate(prevProps, prevState) {
        var me = this;
        if (!(!!window.ActiveXObject || "ActiveXObject" in window)) {//如果不是IE浏览器
            $(".phone_content").each(function () {//使外部样式失效，达到屏蔽效果
                if (this.shadowRoot) {
                    this.shadowRoot.innerHTML = "<style>img{height:auto!important;} *{max-width:100%!important;}</style>" + me.props.html
                } else {
                    this.attachShadow({ mode: 'open' });
                    this.shadowRoot.innerHTML = "<style>img{height:auto!important;} *{max-width:100%!important;}</style>" + me.props.html
                }
            })
        }
    }

    componentWillReceiveProps(nextProps) {
        // console.log(nextProps)
        if(nextProps.editable){
            this.editItem&&this.editItem.setEnabled()
        }
        else{
            return
        }
        // console.log(this.editItem)
    }
    initEditor() {
        const policy_url = config.apiAppName(config.requestApiUrl.getPolicyUrl);
        var customConfig = {
            elementPathEnabled: false,
            serverUrl: config.baseUrl + `admin/oss/ueditor/singleUpload`,
            catchRemoteImageEnable: true,
            // initialContent:`<p style="text-align: center;margin-top:50px;"><span style="font-size: 24px; color: rgb(191, 191, 191);">试试直接把编辑好的图文样式复制粘贴到这儿，有惊喜哦~</span></p>`,
            autoClearinitialContent: true,
        }
        //
        UE.Editor.prototype.placeholder = function (justPlainText) {
            var _editor = this;
            _editor.addListener("focus", function () {
                var localHtml = _editor.getPlainTxt();
                if (localHtml.trim() === justPlainText.trim()) {
                    _editor.setContent("");
                }
            });
            _editor.addListener("blur", function () {
                var localHtml = _editor.getContent();
                if (!localHtml) {
                    _editor.setContent('<p style="text-align: center;margin-top:50px;"><span style="font-size: 24px; color: rgb(191, 191, 191);">' + justPlainText + '</span></p>');
                }
            });
            _editor.ready(function () {
                _editor.fireEvent("blur");
            });
            _editor.addListener('selectionchange', function (type) {
                var localHtml = _editor.getPlainTxt();
                // var html111 = "啊啊"
                
                // console.log(html111.replace(/[^\x00-\xff]/g,"01").length)
                if (localHtml.trim() === justPlainText.trim()) {
                    me.props.inputChange("");
                } else {
                    me.props.inputChange(this.getContent());
                }
                console.log(this.getContent().replace(/[^\x00-\xff]/g,"01").length)
                console.log(this.getContentLength())
                let contentLen = this.getContent().replace(/[^\x00-\xff]/g,"01").length;
                let contentLen2 = this.getContentLength();
                if(contentLen2 >= 62000){
                    message.error('内容过长');
                    me.props.isSubmit({isSubmit:false})
                }else{
                    if(me.props.enableBtn===false){
                        me.props.isSubmit({isSubmit:true})
                    }
                }
            });
        };

        const id = this.props.id;
        var editable = this.props.editable
       
        this.editItem = UE.getEditor(this.props.id, { ...customConfig });
        this.editItem.placeholder("试试直接把编辑好的图文样式复制粘贴到这儿，有惊喜哦~");
        const self = this;
        this.editItem.ready((ueditor) => { 
            this.editItem.setContent(this.props.html)
            if(editable===false){
                this.editItem.setDisabled();
            }
            if (!ueditor) {
                UE.delEditor(id);
                self.initEditor();
            }
        });
        //监听用户输入，用于及时及时反馈，事件中调用父组件的inputChange回调函数
        let me = this;
        this.editItem.addListener('selectionchange', function (type) {
            me.props.inputChange(this.getContent());
        });
        return this.editItem;
    }


    
    render() {
        let { tabList,isShowPhone} = this.state
        let html = this.props.html
        let editable = this.props.editable
        // console.log(editable)
        let customStyle = this.props.style || { width: '100%', height: 400 }
        let that = this;

        function changePhone(e) {
            var that = e.currentTarget;
            var pageY = e.clientY;
            //鼠标按下获取当前容器div的top值
            var oldHeight = parseInt(that.scrollTop);

            document.onmousemove = function (event) {
                var e = event || window.event;
                var height = -(e.clientY - pageY) + oldHeight;
                that.scrollTop = height;
            }
        }
        document.onmouseup = function (e) {
            document.onmousemove = null;
        };
            return (
                <div style={customStyle} className={cx('block')}>
                    <Row>
                        <Col span={isShowPhone ? 14 : 24}>
                            <div className={cx('editor_box')}>
                                <div id={this.props.id} name="content" type="text/plain"></div>
                            </div>
                        </Col>
                        <Col span={1}></Col>
                        {isShowPhone &&
                        <Col span={9}>
                            <Tabs tabPosition={'top'} style={{ width: '100%' }} animated={false}>
                            {tabList.map((item, index) => {
                                    return (
                                        <TabPane tab={item.tabName} key={index} forceRender={true}>
                                            <div className={cx('phone_box', `${item.claBox}`)}>
                                                <div className={cx('top_box', `${item.phone}`)} onMouseDown={(e) => { changePhone(e) }} >
                                                    <div className={cx('mask')}></div>
                                                    <div className={cx('title')}>{this.props.title}</div>
                                                    {this.props.startDate !== '' && this.props.endDate !== '' &&
                                                        <div className={cx('time')}>活动时间：{this.props.startDate}-{this.props.endDate}</div>
                                                    }
                                                    <div className={'phone_content'} dangerouslySetInnerHTML={{ __html: html }}></div>
                                                </div>
                                            </div>
                                        </TabPane>
                                    )
                                })}
                            </Tabs>
                        </Col>
                        }
                    </Row>
                </div>
            )
       
        }
}
export default Ueditor;